package com.blaze.framework.core.util.uitls;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * Servlet请求工具类
 * @author created by Zhou Zongbo on 2025/5/29.
 */
public class ServletRequestUtils {
    private ServletRequestUtils() {
    }

    private static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取请求对象
     * @return HttpServletRequest
     */
    public static Optional<HttpServletRequest> getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        if (Objects.isNull(servletRequestAttributes)) {
            return Optional.empty();
        }
        return Optional.of(servletRequestAttributes.getRequest());
    }

    /**
     * 获取请求(url)中的参数
     * @param name 参数名称
     * @return 参数值
     */
    public static String getRequestParameter(String name) {
        Optional<HttpServletRequest> optHttpServletRequest = getHttpServletRequest();
        return optHttpServletRequest.isEmpty() ? StringUtils.EMPTY : optHttpServletRequest.get().getParameter(name);
    }

}
